package com.virtualperson.service.impl;

import com.virtualperson.service.ObjectStorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Slf4j
@Service
public class LocalStorageServiceImpl implements ObjectStorageService {

    @Value("${app.storage.local.base-path:uploads}")
    private String basePath;

    @Value("${app.storage.local.base-url:http://localhost:8080}")
    private String baseUrl;

    @Override
    public String uploadFile(File file) {
        try {
            // 创建存储目录
            String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path storageDir = Paths.get(basePath, dateStr);
            Files.createDirectories(storageDir);

            // 生成文件名
            String originalName = file.getName();
            String extension = "";
            if (originalName.contains(".")) {
                extension = originalName.substring(originalName.lastIndexOf('.'));
            }
            
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
            String uuid = UUID.randomUUID().toString().substring(0, 8);
            String fileName = String.format("%s_%s%s", timestamp, uuid, extension);

            // 复制文件到存储目录
            Path targetPath = storageDir.resolve(fileName);
            Files.copy(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            // 生成访问URL
            String relativePath = storageDir.resolve(fileName).toString().replace("\\", "/");
            String fileUrl = baseUrl + "/" + relativePath;

            log.info("文件已保存到本地: {}", targetPath.toAbsolutePath());
            log.info("文件访问URL: {}", fileUrl);

            return fileUrl;

        } catch (IOException e) {
            log.error("本地文件存储失败: {}", file.getAbsolutePath(), e);
            throw new RuntimeException("本地文件存储失败: " + e.getMessage());
        }
    }

    @Override
    public void deleteFile(String fileUrl) {
        try {
            // 从URL中提取文件路径
            String relativePath = fileUrl.replace(baseUrl + "/", "");
            Path filePath = Paths.get(basePath, relativePath);

            if (Files.exists(filePath)) {
                Files.delete(filePath);
                log.info("本地文件删除成功: {}", filePath.toAbsolutePath());
            } else {
                log.warn("要删除的文件不存在: {}", filePath.toAbsolutePath());
            }

        } catch (IOException e) {
            log.error("本地文件删除失败: {}", fileUrl, e);
            throw new RuntimeException("本地文件删除失败: " + e.getMessage());
        }
    }

    @Override
    public String getFileUrl(String fileKey) {
        return baseUrl + "/" + fileKey;
    }
} 